import prisma from "../prisma/index.js";

/**
 * 获取代码片段列表
 * @param {string} title - 标题搜索关键字
 * @param {number} skip - 分页偏移量
 * @param {number} take - 每页数量
 * @returns {Promise<Array>} 代码片段数组
 */
export const getCodeSnippetsModel = async (title, skip, take) => {
  try {
    return await prisma.codeSnippet.findMany({
      where: {
        title: {
          contains: title || "",
        },
      },
      select: {
        id: true,
        title: true,
        createdAt: true,
        updatedAt: true,
      },
      skip,
      take,
      orderBy: {
        updatedAt: "desc",
      },
    });
  } catch (err) {
    throw err;
  }
};

/**
 * 获取单个代码片段
 * @param {string} id - 代码片段ID
 * @returns {Promise<Object>} 代码片段详情
 */
export const getCodeSnippetByIdModel = async (id) => {
  try {
    return await prisma.codeSnippet.findUnique({
      where: { id },
      select: {
        id: true,
        title: true,
        code: true,
        createdAt: true,
        updatedAt: true,
      },
    });
  } catch (err) {
    throw err;
  }
};

/**
 * 创建新代码片段
 * @param {string} title - 标题
 * @param {string} code - 代码内容
 * @returns {Promise<Object>} 新创建的代码片段
 */
export const createCodeSnippetModel = async (title, code) => {
  try {
    return await prisma.codeSnippet.create({
      data: {
        title,
        code,
      },
    });
  } catch (err) {
    throw err;
  }
};

/**
 * 更新代码片段
 * @param {string} id - 代码片段ID
 * @param {string} title - 标题
 * @param {string} code - 代码内容
 * @returns {Promise<Object>} 更新后的代码片段
 */
export const updateCodeSnippetModel = async (id, title, code) => {
  try {
    return await prisma.codeSnippet.update({
      where: { id },
      data: {
        title,
        code,
      },
    });
  } catch (err) {
    throw err;
  }
};

/**
 * 删除代码片段
 * @param {string} id - 代码片段ID
 * @returns {Promise<void>}
 */
export const deleteCodeSnippetModel = async (id) => {
  try {
    await prisma.codeSnippet.delete({ where: { id } });
  } catch (err) {
    throw err;
  }
};